package com.dubito.muxin.controller;

import com.dubito.muxin.model.Users;
import com.dubito.muxin.model.vo.UserVO;
import com.dubito.muxin.service.UserService;
import com.dubito.muxin.utils.IMoocJSONResult;
import com.dubito.muxin.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liliang
 * @description:
 * @date 2018/11/18.
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/registOrLogin")
    public IMoocJSONResult registOrLogin(@RequestBody Users users) throws Exception {
        if (StringUtils.isBlank(users.getUsername())
                || StringUtils.isBlank(users.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名或密码不能为空");
        }

        boolean isExist = userService.queryUsernameIsExist(users.getUsername());
        Users result = null;
        if (isExist) {
            result = userService.queryUserForLogin(users.getUsername(), MD5Utils.getMD5Str(users.getPassword()));
            if (result == null) {
                return IMoocJSONResult.errorMsg("用户名或密码不正确");
            }
        } else {
            users.setPassword(MD5Utils.getMD5Str(users.getPassword()));
            result = userService.saveUser(users);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(result, userVO);
        return IMoocJSONResult.ok(userVO);
    }
}
